import GameStorage from "../Data/GameStorage";
import { GameData } from "../Data/GameData";
import GamePanel from "../UI/GamePanel";
import MapManager from "./MapManager";
import { GameState, MainState } from "../Data/GameEnum";
import AssetsManager from "./AssetsManager";
import FailPanel from "../UI/FailPanel";
import WinPanel from "../UI/WinPanel";
import GameEventManager from "./GameEventManager";
import CardFunctions from "../Common/CardFunctions";
import Block from "../Game/Block";
import BlockGroup from "../Game/BlockGroup";
import TimerManager from "./TimerManager";
import Board from "../Game/Board";

const { ccclass, property, executionOrder } = cc._decorator;

/** GameManager */
@ccclass
// 慢一点执行
@executionOrder(100)
export default class GameManager extends cc.Component {
    static Instance: GameManager;

    // gameStart = false;

    gameState: GameState;

    isCanOperate = true;

    下落停止 = false;

    onLoad() {
        GameManager.Instance = this;

        this.Init();
    }

    async Init() {
        // {
        //     // 获取碰撞检测系统：
        //     let manager = cc.director.getCollisionManager();
        //     // 默认碰撞检测系统是禁用的，如果需要使用则需要以下方法开启碰撞检测系统：
        //     manager.enabled = true;
        //     // 默认碰撞检测系统的 debug 绘制是禁用的，如果需要使用则需要以下方法开启 debug 绘制：
        //     manager.enabledDebugDraw = true;
        // }

        GameEventManager.AddListener();

        GameManager.Instance.StartGame();
    }

    async StartGame() {
        // GameStorage.initData();
        await new Promise(res => this.scheduleOnce(res, 0.1));

        GameData.InitData();

        GameData.CurrentLevelData = AssetsManager.Levels[GameData.CurrentLevel];
        // console.log(`GameData.CurrentLevelData`, GameData.CurrentLevelData);

        MapManager.Instance.initCard();
        GamePanel.Instance.ShowOn();

        GameManager.Instance.gameState = GameState.待机;
    }

    async ReStartGame() {
        cc.director.loadScene("GameScene");
    }

    async ExitGame() {
        cc.director.loadScene("MainScene");
    }

    async NextStage() {
        cc.director.loadScene("MainScene");
    }

    Win() {
        GameManager.Instance.Pause();
        WinPanel.Instance.ShowOn();
    }

    Fail() {
        GameManager.Instance.Pause();
        FailPanel.Instance.ShowOn();
    }

    Pause() {
        GameData.gamePause = true;

    }

    // 吃海底捞
    async Main() {
        // 1-等待叫号
        // 2-排到号，上桌
        // 3-检测是否上面等候区有凳子空了
        // 4-没空就结束循环
        // 5-空了就撤凳子
        // 6-撤完凳子在检测新的客人是否有新的匹配
        // 7-没有匹配就结束循环
        // 8-有匹配就循环第2部-上桌

        if (GameData.mainState === MainState.空闲) {
        }
        else if (GameData.mainState === MainState.上桌) {
            GameManager.Instance.上桌();
        }
        else if (GameData.mainState === MainState.上桌完成) {
            console.log("上桌完成");

            // GameManager.Instance.检测是否需要撤凳子();

            GameManager.Instance.撤凳子();
        }
        else if (GameData.mainState === MainState.撤凳子) {

        }
        else if (GameData.mainState === MainState.撤凳子完成) {
            if (GameManager.Instance.后面是否有新凳子()) {
                GameManager.Instance.后面凳子亮出来();
            }
            else {
                GameManager.Instance.回合结束();
            }
        }
    }

    async 回合结束() {
        if (GameManager.Instance.是否成功()) {
            WinPanel.Instance.ShowOn();
        }

        if (GameManager.Instance.是否失败()) {
            FailPanel.Instance.ShowOn();
        }
    }

    是否成功() {
        if (GameData.arrBoard.length === 0) {
            return true;
        }
        else {
            return false;
        }
    }

    是否失败() {
        return false;
    }

    后面是否有新凳子() {
        for (let index_board = 0; index_board < GameData.arrBoard.length; index_board++) {
            const board: Board = GameData.arrBoard[index_board];
            console.log("board", board);
            console.log("board.cardList", board.cardList);

            const isBoardCover = CardFunctions.IsBoardCover(board);
            if (isBoardCover !== board.isCover) {
                return true;
            }
        }

        return false;
    }


    async 后面凳子亮出来() {
        CardFunctions.SetAllBoardCover();

        GameData.mainState = MainState.上桌;
        GameManager.Instance.Main();
    }

    async 撤凳子() {
        console.log("撤凳子");

        for (let index = 0; index < GameData.arrBoard.length; index++) {
            const board: Board = GameData.arrBoard[index];
            let is撤凳子 = board.Check撤凳子();
            console.log("is撤凳子", is撤凳子);

            if (is撤凳子) {
                GameData.撤凳子list.push(board);
            }
        }

        console.log(`GameData.撤凳子list`, GameData.撤凳子list);
        // return

        let count = 0;
        for (let index = 0; index < GameData.撤凳子list.length; index++) {
            const board: Board = GameData.撤凳子list[index];

            // console.log("item.card", item.card);
            // item.card.node.scale = 0.5;
            // item.card.node.active = true;

            console.log("board.cardList---", board.cardList);

            await board.Dead();

            count++;
        }

        if (count >= GameData.撤凳子list.length) {
            GameData.撤凳子list = [];
            GameData.mainState = MainState.撤凳子完成;
            GameManager.Instance.Main();
        }
    }

    /** 上桌 */
    async 上桌() {
        console.log("上桌");

        let arrCardGroup_grid = CardFunctions.Get_arrCardGroup_grid()
        console.log("arrCardGroup_grid", arrCardGroup_grid);

        for (let index2 = 0; index2 < arrCardGroup_grid.length; index2++) {
            const blockGroup: BlockGroup = arrCardGroup_grid[index2];
            blockGroup.准备上桌();
        }

        console.log("GameData.装填list", GameData.装填list);

        let count = 0;
        for (let index = 0; index < GameData.装填list.length; index++) {
            const item = GameData.装填list[index];

            console.log("item.card", item.card);
            // item.card.node.scale = 0.5;
            // item.card.node.active = true;

            let p1 = item.block.node.parent.convertToWorldSpaceAR(item.block.node.position);
            let p2 = item.card.node.parent.convertToNodeSpaceAR(p1);

            cc.tween(item.card.node)
                .bezierTo(0.3, item.card.node.position, cc.v2(400, 600), p2)
                .call(() => {
                    item.card.node.parent = item.block.node;
                    item.card.node.position = cc.v3(0, 0, 0);
                    item.card.node.scale = 1;

                    item.block.is装填完成 = true;

                    if (item.blockGroup.是否该结账了()) {
                        item.blockGroup.结账();
                    }
                })
                .start();
            await TimerManager.AwaitTime(0.3);

            count++;
        }

        if (count >= GameData.装填list.length) {
            GameData.装填list = [];
            GameData.mainState = MainState.上桌完成;
            GameManager.Instance.Main();
        }
    }

    /** 加载主场景 */
    static LoadMainScene() {
        GameData.ClearData();
    }

    static ReStart() {
        GameData.ClearData();
        GamePanel.Instance.ShowOff();
    }

    static SaveMapData() {
        GameStorage.data.GameData.mapData = {};
        GameStorage.saveData();
    }

    /** 新的一局 */
    NewGame() {
        cc.audioEngine.playMusic(AssetsManager.Audios[`castleDefense`], true);
    }

    /** 回合结束 */
    RoundEnd() {
        console.log(`回合结束-------------------------------------------`);

        GameManager.Instance.NewRound();
    }

    /** 新的下落回合 */
    NewRound() {
        console.log(`新的回合-------------------------------------------`);

        GameManager.Instance.gameState = GameState.待机;
    }

    /** 回合结束 */
    static RoundEnd() {
        GameData.IsCanOperate = true;

        // GameStorage.ArrCardGroupsToMapData();

        GamePanel.Instance.Refresh();
    }
}

/** 调试 */
window["GameManager"] = GameManager;